package com.airS.task.fileMgr.service.gk.impl;

import com.airS.task.fileMgr.common.page.Page;
import com.airS.task.fileMgr.example.gk.RoleExample;
import com.airS.task.fileMgr.mapper.gk.RoleMapper;
import com.airS.task.fileMgr.model.gk.Role;
import com.airS.task.fileMgr.query.gk.RoleQuery;
import com.airS.task.fileMgr.service.gk.RoleService;
import com.airS.task.fileMgr.utils.page.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by alan on 2017/3/14.
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Role queryRoleById(Integer id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public Page<Role> queryRoles(RoleQuery query) {
        PageUtil.startPage(query);
        List<Role> Roles = roleMapper.selectByExample(assemblyRoleExample(query));
        return new Page<Role>(Roles);
    }

    @Override
    public Map<Integer, Role> getAllRoleToMap(){
        Map<Integer, Role> roleMap = new HashMap<Integer, Role>();
        for(Role role : getAllRoleToList()){
            roleMap.put(role.getRoleId(), role);
        }
        return roleMap;
    }

    @Override
    public List<Role> getAllRoleToList(){
        return roleMapper.selectByExample(new RoleExample());
    }

    @Override
    public Integer addRole(Role role) {
        roleMapper.insert(role);
        return role.getRoleId();
    }

    @Override
    public Integer updateRoleById(Role role) {
        return roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public Integer delRoleById(Integer id) {
        return roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Integer delRoleByIds(List<Integer> ids) {
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        criteria.andRoleIdIn(ids);
        return roleMapper.deleteByExample(example);
    }

    private RoleExample assemblyRoleExample(RoleQuery query){
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        if(StringUtils.hasText(query.getRoleName())){
            criteria.andRoleNameLike("%" + query.getRoleName() + "%");
        }
        example.setOrderByClause("create_time desc");
        return example;
    }
}
